from django.core.exceptions import ObjectDoesNotExist
from django.contrib.sites.models import Site
from django.contrib.syndication.feeds import Feed
from django.contrib.contenttypes.models import ContentType
from django.utils.feedgenerator import Atom1Feed
from django.conf import settings

from models import Comment
from news.models import News
from projects.models import Project
from cab.models import Snippet

commented_obj = {"news":News, "projects":Project, "snippets":Snippet}

class GenericCommentsRSS(Feed):
    categories = ("python", "pygame", "open source", "game", "comment")
    title_template = 'comments/feed_title.html'
    description_template = 'comments/feed_description.html'
    def items(self, obj):
        if not obj:
            myitems = Comment.user_comments.all()
        elif isinstance(obj, basestring):
            ctype = ContentType.objects.get_for_model(commented_obj[obj])
            myitems = Comment.user_comments.filter(content_type=ctype)
        else:
            ctype = ContentType.objects.get_for_model(obj)
            myitems= Comment.user_comments.filter(content_type__pk=ctype.id, 
                                            object_id=obj.id) 
        return (myitems.count() > settings.COMMENTS_PER_FEED and
                myitems[:settings.COMMENTS_PER_FEED] or myitems)
                                       
    def item_author_name(self, item):
        # exclude auto comments
        return item.user.get_profile().display_name
    
    def item_author_link(self, item):
        return "/profiles/%s/" % item.user.username
    
    def item_pubdate(self, item):
        return item.created

    def get_object(self, args):
        if not args:
            return None
        elif args[0] not in commented_obj or len(args) > 2:
            raise ObjectDoesNotExist
        elif len(args) == 1:
            return args[0]
        elif len(args) == 2:
            if args[0] == "snippets":
                return Snippet.objects.get(id=args[1])
            return commented_obj[args[0]].objects.get(slug__exact=args[1])
        raise ObjectDoesNotExist

    def title(self, obj):
        if obj:
            return 'Comments on "%s"' % obj
        return "All comments on %s" % Site.objects.get_current()

    def link(self, obj):
        if not obj:
            return "/"
        elif isinstance(obj, basestring):
            return "/%s/" % obj
        else:
            return obj.get_absolute_url()

    def description(self, obj):
        if obj:
            return 'Comments on "%s"' % obj
        return "All comments on %s" % Site.objects.get_current()


class GenericCommentsAtom(GenericCommentsRSS):
    feed_type = Atom1Feed
    subtitle = GenericCommentsRSS.description
